module ESI
 
  # :startdoc:
  # esi server is a reverse proxy caching server.  It will forward all requests to app servers
  # by processing a config_file that specifies routes such as
  #
  # content:
  #   host: 127.0.0.1
  #   port: 3000
  #   match_url: ^\/(content|samples|extra).*
  # default:
  #   host: 127.0.0.1
  #   port: 3001
  #
  # this sample configuration will route all urls starting with /content, /samples, or /extras
  # to the server running at 127.0.0.1 on port 3000
  # everything else that matches the .* will be routed to the server running on port 3001
  # optionally the caching duration can be specificied explicity for each host
  #
  # default:
  #   host: 127.0.01
  #   port: 3001
  #   cache_ttl: 300
  #
  # this example will cache all requests for 300 seconds
  # :enddoc:

  class Router 

    def initialize( root, config )    
      @config = config
      @routes = @config.router(root)
      $logger.warn "Missing default in configuration" unless @routes
    end

    # return a uri given a request_uri
    def url_for( request_uri )
      return request_uri if request_uri.match(/http:\/\//)
      config = route_for_uri( request_uri )
      # build a url given a valid config or abort 404 not found
      "http://" + (config[:host] + ":" + (config[:port] || "").to_s + "/" + request_uri).squeeze("/")
    end

    def cache_ttl( request_uri )
      @cache_config ||= @routes.configuration( request_uri )
      @cache_config ||= @config.config[:cache_ttl] # or default
      (config[:cache_ttl] || 600).to_i
    end

    def route_for_uri( request_uri )
      @routes.route_for_uri(request_uri)
    end
  end

end
